package com.siao.core
{
	import com.siao.display.LayoutElement;
	import com.siao.utils.math.round;
	
	import flash.events.Event;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.utils.getTimer;
	
	/**
	 * 性能监控
	 * @author SiaoLeon
	 */
	public class Performance extends LayoutElement
	{
		// -------------------------------------------------------------------------------------------------------- 静态常量
		
		// -------------------------------------------------------------------------------------------------------- 静态变量
		
		// -------------------------------------------------------------------------------------------------------- 静态方法
		
		// -------------------------------------------------------------------------------------------------------- 静态函数
		
		// -------------------------------------------------------------------------------------------------------- 属性
		
		// -------------------------------------------------------------------------------------------------------- 变量
		
		private var txtFPS:TextField;
		
		private var txtMemory:TextField;
		
		private var timer:Number = 0;
		
		private var frames:Number = 0;
		
		// -------------------------------------------------------------------------------------------------------- 构造
		
		/**
		 * 构造函数
		 */
		public function Performance(color:uint=0XFFFF00)
		{
			super();
			
			this.txtFPS = new TextField();
			this.txtFPS.defaultTextFormat = new TextFormat("simsun", 14, color);
			this.txtFPS.autoSize = TextFieldAutoSize.LEFT;
			this.addChild(this.txtFPS);
			
			this.txtMemory = new TextField();
			this.txtMemory.defaultTextFormat = new TextFormat("simsun", 14, color);
			this.txtMemory.autoSize = TextFieldAutoSize.LEFT;
			this.txtMemory.y = 16;
			this.addChild(this.txtMemory);
		}
		
		// -------------------------------------------------------------------------------------------------------- 方法
		
		// -------------------------------------------------------------------------------------------------------- 函数
		
		override protected function onAddedToStage():void
		{
			this.timer = getTimer();
			
			this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function onEnterFrame(event:Event):void
		{
			var current:Number = (getTimer() - this.timer) / 1000;
			this.frames++;
			
			this.txtFPS.text = "FPS: " + (Math.floor((this.frames / current) * 10.0) / 10.0);
			this.timer = getTimer();
			this.frames = 0;
			
			if (System.privateMemory >= 1024 * 1024)
			{
				this.txtMemory.text = "Memory：" + round(System.privateMemory / 1024 / 1024, 2) + "MB";
			}
			else if (System.privateMemory >= 1024)
			{
				this.txtMemory.text = "Memory：" + round(System.privateMemory / 1024, 2) + "KB";
			}
			else
			{
				this.txtMemory.text = "Memory：" + System.privateMemory + "B";
			}
		}
	
	}
}
